<template>
  <el-card class="box-card">
    <el-breadcrumb separator-class="el-icon-arrow-right" style="width: 300px">
      <el-breadcrumb-item style="font-size: 16px">首页</el-breadcrumb-item>
      <el-breadcrumb-item style="font-size: 16px">权限管理</el-breadcrumb-item>
      <el-breadcrumb-item style="font-size: 16px"
        >角色列表管理</el-breadcrumb-item
      >
    </el-breadcrumb>
    <div class="addUser" style="margin-top: 20px">
      <!-- 对话框组件  :visible.sync(设置是否显示对话框) width(设置对话框的宽度)
:before-close(在对话框关闭前触发的事件) -->
      <el-dialog
        title="添加角色"
        :visible.sync="addDialogVisible"
        width="40%"
        @close="addDialogClosed()"
      >
        <!-- 对话框主体区域 -->
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="80px"
          style="padding: 10px 20px"
        >
          <el-form-item label="角色名称" prop="name" style="height: 50px">
            <el-input v-model="addForm.name" style="width: 50%"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="describe" style="height: 50px">
            <el-input v-model="addForm.describe" style="width: 50%"></el-input>
          </el-form-item>
        </el-form>
        <!-- 对话框底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addCancel">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <el-button
        v-if="showAdd"
        type="primary"
        @click="addDialogVisible = true"
        style="float: right; margin-top: -41px; margin-right: 60px"
        >添加角色</el-button
      >
    </div>
    <el-table
      :data="userData"
      border
      style="width: 1051px; margin-left: 10px; margin-top: 40px"
      :header-cell-style="headClass"
    >
      <el-table-column label="序号" width="110" type="index" align="center">
      </el-table-column>
      <el-table-column label="角色名称" width="300" prop="name" align="center">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.roleName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色描述" width="350" prop="name" align="center">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.description }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="290" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="showEdit"
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="showEditDialog(scope.row.id)"
          ></el-button>
          <el-button
            v-if="showRemove"
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="removeUserById(scope.row.id)"
          ></el-button>
          <el-button
            v-if="showAssign"
            size="mini"
            type="warning"
            icon="el-icon-star-off"
            @click="assignPrmissions(scope.row)"
            >分配权限</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      title="修改信息"
      :visible.sync="editDialogVisible"
      width="400px"
      @close="editDialogClosed"
    >
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="describe">
          <el-input v-model="editForm.describe" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="分配权限"
      ref="assignFormRef"
      :visible.sync="assignDialogVisible"
      width="400px"
      @close="assignDialogClosed"
    >
      <el-tree
        :data="assignForm"
        show-checkbox
        node-key="id"
        :check-strictly="isCheck"
        default-expand-all
        :props="defaultProps"
        ref="treeRef"
      >
      </el-tree>
      <div slot="footer">
        <el-button @click="assignCancel">取 消</el-button>
        <el-button type="primary" @click="assignRights()">确 定</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import qs from "qs";
import throttling from "@/public/throttling.js";
export default {
  data() {
    return {
      // 按钮显示隐藏
      showAdd: true,
      showEdit: true,
      showRemove: true,
      showAssign: true,
      isCheck: false,
      // 所有权限的数据
      rightsList: [],
      // 树形控件 -> 默认选中的节点id值数组
      defKeys: [],
      // 控制修改院校
      editDialogVisible: false,
      // 添加用户
      addDialogVisible: false,

      addForm: {
        name: "",
        describe: "",
      },
      addFormRules: {
        name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
        describe: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      // 修改用户的表单数据
      editForm: {
        id: "",
        name: "",
        describe: "",
      },
      // 属性
      editFormRules: {
        name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
        describe: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      //初始分页条件
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 9,
        count: 0,
      },
      // 保存请求回来的用户列表数据
      userData: [
        {
          // order: 1,
          description: "拥有全部权限",
          id: null,
          roleName: "超级管理员",
        },
      ],
      // 分配权限form
      //   分配权限
      roleName: "",
      assignDialogVisible: false,
      assignForm: [
        {
          id: 1,
          permission: "学校管理",
          children: [
            {
              id: 3,
              permission: "删除推荐院校",
            },
            {
              id: 4,
              permission: "编辑推荐院校",
            },
          ],
        },
        {
          id: 2,
          permission: "专业管理",
          children: [
            {
              id: 5,
              permission: "删除推荐专业",
            },
            {
              id: 6,
              permission: "编辑推荐专业",
            },
          ],
        },
      ],
      // 规定数组参数  跟后台事先确定好
      defaultProps: {
        children: "children",
        label: "permission",
      },

      dialogTableVisible: false,
      dialogFormVisible: false,
      form: {
        name: "",
        region: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
      },
      formLabelWidth: "120px",
    };
  },
  methods: {
    // 表格表头
    headClass() {
      //表头居中显示
      return "color:rgba(255,101,0);font-weight:bold;font-size:16px";
    },
    // 分配权限
    handleCheckAllChange(val) {
      this.checkedCities = val ? cityOptions : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cities.length;
    },
    handleSelect(key, keyPath) {
      console.log(key, keyPath);
    },
    handleCurrentChange(page) {
      this.queryInfo.pagenum = page;
      console.log("跳转了");
      // 重新按照pagenum发送请求 请求最新的数据
      this.getUserList_Token();
    },
    // 得到角色列表
    getUserList_Token() {
      const token = window.sessionStorage.getItem("tokenvalue");
      this.$axios.defaults.headers.common["satoken"] = token;
      this.$axios.get("/back/permission/roles").then((res) => {
        console.log(res);
        if (res.data.status === 666) {
          this.$message.error("请先登录");
          this.$router.replace("/login");
        } else if (res) {
          console.log(res);
          this.$message.success("获取角色列表成功！");
          this.userData = res.data;
        }
      });
    },
    // 添加
    addDialogClosed() {
      // 对话框关闭之后，重置表单
      this.$refs.addFormRef.resetFields();
    },

    addCancel() {
      this.addDialogVisible = false;
      this.$message("取消修改");
    },
    showAddDialog() {
      //显示弹出窗
      this.editDialogVisible = true;
    },
    addUser: throttling(function () {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return;
        else {
          this.$axios
            .post(
              "/back/permission/role",
              qs.stringify({
                roleName: this.addForm.name,
                description: this.addForm.describe,
              })
            )
            .then((res) => {
              console.log(res);
              if (res.data.status !== 200) {
                this.$message.error("添加角色失败，请重试");
              }
              this.$message.success("添加角色成功！");
              this.addDialogVisible = false;
              this.getUserList_Token();
            });
        }
      });
    }, 1000),
    // 修改
    showEditDialog(id) {
      //将获取到的数据保存到数据editForm中
      this.editForm.id = id;
      //显示弹出窗
      this.editDialogVisible = true;
    },
    editDialogClosed() {
      // 对话框关闭之后，重置表单
      this.$refs.editFormRef.resetFields();
    },

    cancel() {
      this.editDialogVisible = false;
      this.$message("取消修改");
    },
    editUser: throttling(function () {
      // // 用户点击修改表单中的确定按钮之后，验证表单数据
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) return;
        else {
          this.$axios
            .put(
              "/back/permission/role",
              qs.stringify({
                id: this.editForm.id,
                roleName: this.editForm.name,
                description: this.editForm.describe,
              })
            )
            .then((res) => {
              console.log(res);
              //修改成功的提示
              this.$message.success("修改角色成功");
              //关闭对话框
              this.editDialogVisible = false;
              //重新请求最新的数据
              this.getUserList_Token();
            });
        }
        // 发送请求 完成修改用户的操作
      });
    }, 1000),
    removeUserById(id) {
      //弹出确定取消框，是否删除用户
      this.$confirm("请问是否要永久删除该角色", "删除提示", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确认删除",
        cancelButtonText: "取消",
      })
        .then(() => {
          //发送请求根据id完成删除操作
          this.$axios.delete("/back/permission/role/" + id).then((res) => {
            console.log(res);
            //判断如果删除失败，就做提示
            if (res.data.code !== 200) return this.$message.error(res.data.msg);
            //修改成功的提示
            this.$message.success("删除角色成功");
            //重新请求最新的数据
            this.getUserList_Token();
          });
        })
        .catch((action) => {
          this.$message({
            type: "info",
            message: action === "cancel" ? "取消删除" : "放弃删除",
          });
        });
    },
    // 分配权限
    assignPrmissions: throttling(function (roles) {
      this.assignDialogVisible = true;
      this.roleName = roles.roleName;
      // 查询所有权限 当前用户具有的权限id
      this.$axios
        .get("/back/permission/" + roles.roleName, {
          headers: {
            satoken: window.sessionStorage.getItem("tokenvalue"),
          },
        })
        .then((res) => {
          this.assignForm = res.data.data;
          const idList = res.data.date1;
          this.isCheck = true;
          this.$nextTick(() => {
            this.$refs.treeRef.setCheckedKeys(res.data.data1); //给树节点赋值
            this.isCheck = false; //重点： 赋值完成后 设置为false
          });
          console.log(this.assignForm);
        });
    }, 1000),
    assignDialogClosed() {
      this.$refs.treeRef.resetFields();
    },
    assignCancel() {
      this.$message("取消修改");
      this.assignDialogVisible = false;
    },
    // 提交
    assignRights: throttling(function () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idStr = keys.join(",");
      console.log(idStr);
      this.$axios
        .put(
          "/back/permission",
          qs.stringify({
            name: this.roleName,
            rights: idStr,
          })
        )
        .then((res) => {
          this.$message.success("分配权限成功");
          this.getUserList_Token();
          this.assignDialogVisible = false;
        });
    }, 1000),
  },
  created() {
    this.getUserList_Token();
    this.$axios.get("/back/permission/role/updateButton").then((res) => {
      if (res.data.code === 500) {
        this.showEdit = false;
      }
    });
    this.$axios.get("/back/permission/roleButton").then((res) => {
      if (res.data.code === 500) {
        this.showRemove = false;
      }
    });
    this.$axios.get("/back/permission/putButton").then((res) => {
      if (res.data.code === 500) {
        this.showAssign = false;
      }
    });
    this.$axios.get("/back/permission/role/addButton").then((res) => {
      if (res.data.code === 500) {
        this.showAdd = false;
      }
    });
  },
};
</script>

<style scoped>
.box-card {
  position: relative;
  margin: 22px auto;
  min-height: 550px;
}
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.el-table {
  margin-top: 20px;
}

.el-dialog .el-dialog__body {
  padding: 10px 20px;
}

.el-form-item {
  margin-bottom: 10px;
}
</style>